//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { store } from '@/store'
//引入接口
import { UserApi } from '@/api/user/index'
//引入数据类型
import type { LoginForm, LoginResponseData, UserResponseData } from '@/api/user/type'
import type { UserState } from './types/user'
//引入操作本地存储的工具方法
import { useCache } from '@/hooks/web/useCache'
//引入路由（常量路由）
import remainingRouter from '@/router/modules/routes'

const { wsCache } = useCache()

//创建用户小仓库
export const useUserStore = defineStore('User', {
  //小仓库存储数据
  state: (): UserState => {
    return {
      token: wsCache.get('TOKEN'), //获取用户唯一标识token
      menuRoutes: remainingRouter, //仓库存储生成菜单需要的数组（路由）
      username: '',
      avatar: '',
      buttons: []
    }
  },
  //异步、逻辑
  actions: {
    //用户登录的方法
    async userLogin(data: LoginForm) {
      const result: LoginResponseData = await UserApi.reqLogin(data)
      //成功
      if (result.code == 200) {
        //在pinia仓库储存一下token
        this.token = result.data.token as string
        //本地存储持久化存储一份
        wsCache.set('TOKEN', result.data.token as string)
        //保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data.message))
      }
    },
    //获取用户登录信息的方法
    async userInfo() {
      const result: UserResponseData = await UserApi.reqUserInfo()
      //如果获取用户信息成功，储存用户信息
      if (result.code == 200) {
        this.username = result.data.checkUser.username
        this.avatar = result.data.checkUser.avatar
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败。')
      }
    },
    //退出登录的方法
    async userLogout() {
      this.token = ''
      this.username = '请登录'
      this.avatar =
        'https://gd-hbimg.huaban.com/689a639c005bddbad7bae709038b4fff36b8c9f2cdc8-PTyTst_fw236'
      wsCache.delete('TOKEN')
    }
  },
  getters: {}
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
